package com.ktjy.actual.actual02;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Proxy;

public class ValidationProxy {
    public static Object newInstance(Object target) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new ValidationInvocationHandler(target) //代理的对象
        );
    }

    private static class ValidationInvocationHandler implements InvocationHandler {
        private final Object target;

        public ValidationInvocationHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //获取这个对象接口的所有方法
            Method[] methods = target.getClass().getInterfaces()[0].getMethods();
            for (Method m : methods) {
                //判断方法名和参数的个数是否一致
                if (m.getName().equals(method.getName()) && m.getParameterCount() == args.length) {
                    //获取这个方法的所有参数
                    Parameter[] parameters = m.getParameters();
                    for (int i = 0; i < parameters.length; i++) {
                        //判断参数上是否有@Validate注解
                        if (parameters[i].isAnnotationPresent(Validate.class)) {
                            //获取参数上的注解
                            Validate validate = parameters[i].getAnnotation(Validate.class);
                            Object arg = args[i];
                            //判断参数类型 判断参数是否为Double
                            if (arg instanceof Double) {
                                Double value = (Double) arg;
                                if (validate.notEmpty() && value == null) {
                                    throw new ValidationException("参数不能为空");
                                }
                                if (!Double.isInfinite(validate.minValue())&& value<validate.minValue()){
                                    throw new ValidationException("参数不能小于"+validate.minValue());
                                }
                                if (!Double.isInfinite(validate.maxValue())&& value>validate.maxValue()){
                                    throw new ValidationException("参数不能大于"+validate.maxValue());
                                }
                            }else {
                                throw new ValidationException("参数类型不匹配");
                            }
                        }
                    }
                }
            }
            return method.invoke(target, args);
        }
    }
}